package com.example.bawolf.leetcode;

import org.springframework.util.StringUtils;

import java.lang.reflect.Array;
import java.util.*;

/**
 * StringTest
 *
 * @author zhougf
 * @date 2020/03/04
 */
public class StringTest {
    public int lengthOfLongestSubstring(String s) {
        int strLength = s.length();
        int initMaxLength = 0;
        for (int i = 0; i < strLength; i++) {
            for (int j = i + 1; j <= strLength; j++) {
                if (!isRepeatString(s, i, j)) {
                    initMaxLength = Math.max(initMaxLength, j - i);
                }
            }
        }
        return initMaxLength;
    }

    public Boolean isRepeatString(String str, int start, int end) {
        if (StringUtils.isEmpty(str)) {
            return false;
        }
        Set<Character> characterSet = new HashSet<>(8);
        for (int i = start; i < end; i++) {
            if (characterSet.contains(str.charAt(i))) {
                return true;
            }
            characterSet.add(str.charAt(i));
        }
        return false;
    }

    public int lengthOfLongestSubstring2(String s) {
        if (s.length() == 0) {
            return 0;
        }
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int max = 0;
        int left = 0;
        for (int i = 0; i < s.length(); i++) {
            if (map.containsKey(s.charAt(i))) {
                left = Math.max(left, map.get(s.charAt(i)) + 1);
            }
            map.put(s.charAt(i), i);
            max = Math.max(max, i - left + 1);
        }
        return max;

    }

}
